<script setup lang="ts">
import { computed, defineAsyncComponent } from 'vue';
import gfm from '@bytemd/plugin-gfm';
import highlight from '@bytemd/plugin-highlight';

import 'bytemd/dist/index.css';
import 'highlight.js/styles/github.css';

const props = defineProps<{ content: string }>();

const plugins = computed(() => [gfm(), highlight()]);

const BytemdViewer = defineAsyncComponent(async () => {
  const mod = await import('@bytemd/vue-next');
  return (mod as any).Viewer;
});

function preprocessMarkdown(raw: string): string {
  if (!raw) return '';

  // 规范化围栏：确保 ``` 独占一行，避免被当作普通文本
  const text = raw.replace(/\s*```\s*/g, '\n```\n');

  // 如果文本中存在“明显的 HTML 片段”，且没有整体围栏，则尝试包裹为代码块
  const hasFence = /```[\s\S]*?```/.test(text);
  const htmlLike = /<\/?[a-zA-Z][^>]*>|<!DOCTYPE|<html|<head|<body|<script|<style/i.test(text);

  if (!hasFence && htmlLike) {
    return '```html\n' + text.trim() + '\n```';
  }

  // 若已存在围栏，或者不明显是 HTML，则原样交由插件处理
  return text.trim();
}

const renderContent = computed(() => preprocessMarkdown(props.content));
</script>

<template>
  <BytemdViewer :value="renderContent" :plugins="plugins" :sanitize="true" />
</template>

<style scoped>
:deep(.bytemd) {
  border: none;
}
:deep(.bytemd .bytemd-body) {
  padding: 0;
}
</style> 